import Data.List (findIndex)

type TimeStamp = Int
type ID = Int

splitAll :: Eq a => [a] -> [a] -> [[a]]
splitAll _ [] = []
splitAll delims xs = 
    token : splitAll delims rest
    where
        isDelimiter = (`elem` delims)
        token       = takeWhile (not . isDelimiter) xs
        rest        = dropWhile isDelimiter $ dropWhile (not . isDelimiter) xs

parseInput :: String -> (TimeStamp, [ID])
parseInput string = 
    (timestamp, ids)
    where
        timestamp = read . head . lines $ string
        ids = map read . splitAll ",x" . last . lines $ string

departTimeStamps :: ID -> [TimeStamp]
departTimeStamps id = [0,id..]

minDepartTimeStamp :: TimeStamp -> ID -> TimeStamp
minDepartTimeStamp targetTime id = 
    head . dropWhile (<targetTime) . departTimeStamps $ id

unwrap :: Maybe a -> a
unwrap (Just v) = v

minValue :: (TimeStamp, [ID]) -> Int
minValue (targetTime, ids) = 
    minID * (minDepTime - targetTime)
    where
        minDepTimes = map (minDepartTimeStamp targetTime) ids
        minDepTime = minimum minDepTimes
        minID = ids !! (unwrap . findIndex (==minDepTime) $ minDepTimes)

main :: IO () 
main = do
    input <- readFile "input.txt"
    print . minValue . parseInput $ input

